/**
 * 
 */
package userController;



import java.io.IOException;
import java.net.URL;
import java.sql.SQLException;
import java.util.ResourceBundle;









import mail.MailSender;

import org.apache.commons.lang3.StringUtils;

import constants.Constants;
import encryption.Encrypt;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import userEntity.CustomerEntity;
import userEntity.EmployeeEntity;
import userLogic.CreateUserLogic;
import validator.Validator;
/**
 * @author Yokesh Kumar
 *
 */
public class CreateUserController implements Initializable{

	@FXML
	private TextField name;
	@FXML
	private TextField phoneNumber;
	@FXML
	private TextField emailAddress;
	@FXML
	private TextField address;
	@FXML
	private TextField postalcode;
	@FXML
	private TextField loginId;
	@FXML
	private PasswordField pwd;
	@FXML
	private PasswordField confirmPwd;
	@FXML
	private CheckBox clubMembership;
	@FXML
	private ChoiceBox<String> designaton; 
	@FXML
	private Label message,message1,message2,message4,Emessage;
	@FXML
	private Label phoneInvalid,nameInvalid,emailIdInvalid,addressInvalid,postalInvalid,loginIdInvalid,designationInvalid,pwdInvalid,confirmPwdInvalid;

	@FXML
	private Button createEmployeSubmit;
	
	private Integer invalid=0;

	@FXML
	private StackPane createCustomerStackPane;

	private Stage createUserStage;

	public void SetStage(Stage Stage)
	{
		this.createUserStage=Stage;
	}

	public void setCreateCustomerStackPane(Node node) {
		createCustomerStackPane.getChildren().setAll(node);
	}
	/**
	 * This method is executed when user clicks submit button
	 * while creating the login
	 */
	@FXML
	public void createCustomer(ActionEvent event){
		message.setText("");
		CreateUserLogic createUserLogic = new CreateUserLogic();
		CustomerEntity customer = new CustomerEntity();
		String msg = "";
		if(phoneNumber != null && !phoneNumber.getText().isEmpty()){
			msg = createUserLogic.validateAndCheckPhNo(phoneNumber.getText().trim());
			if(!msg.equalsIgnoreCase("")){
				message.setText(msg);
			}
			else{
				String phNo = "+1";
				phNo = phNo.concat(phoneNumber.getText().trim());
				customer.setPhoneNumber(phNo);
			}
		}
		else{
			message.setText("phone Number is required");
		}
		if(emailAddress != null && !emailAddress.getText().isEmpty()){
			if(!Validator.validateEmailID(emailAddress.getText().trim())){
				message.setText("Please enter a valid email ID");
			}
			else{
				customer.setEmailID(emailAddress.getText().trim());
			}
		}
		else{
			message.setText("Email address is required");
		}
		if(name != null && !name.getText().isEmpty()){
			if(!Validator.validateName(name.getText().trim())){
				message.setText("Name is not valid");
			}
			else{
				customer.setName(name.getText().trim());
			}
		}
		else{
			message.setText("Name is required");
		}
		if(loginId != null && !loginId.getText().isEmpty()){
			if(!createUserLogic.checkLoginId(loginId.getText().trim())){
				message.setText("LoginId is not available. Please enter a differnet loginId");
			}
			else{
				customer.setLoginId(loginId.getText().trim());
			}
		}
		else{
			message.setText("Login ID is required");
		}
		if(pwd != null && !pwd.getText().isEmpty() && confirmPwd != null && !confirmPwd.getText().isEmpty()){
			if(!Validator.verifyPwd(pwd.getText().trim(), confirmPwd.getText().trim())){
				message.setText("Password fields doesn't match");
			}
			else{
				customer.setPwd(pwd.getText().trim());
			}
		}
		else{
			message.setText("pwd is required");
		}
		if(address != null && !address.getText().isEmpty()){
			customer.setAddress(address.getText().trim());
		}
		if(postalcode != null && !postalcode.getText().isEmpty()){
			customer.setPincode(postalcode.getText().trim());
		}

		if(message == null || message.getText().isEmpty()){
			try {
				boolean success = createUserLogic.createCustomer(customer);
				if(success){
					msg = "LoginID successfully created";
					if(customer.getEmailID() != null && !StringUtils.isEmpty(customer.getEmailID())){
						String text = "Dear Customer, Your login is successfully created. Your new login Id " + customer.getLoginId() + " your password " + Encrypt.decrypt(customer.getPwd());
						String subject = "Welcome to SuperRent";
						MailSender.send(text, subject, customer.getEmailID());
					}
					if(clubMembership.isSelected()){
						try {
							Navigator.setPhoneNumber(customer.getPhoneNumber());
							setCreateCustomerStackPane((Node) FXMLLoader.load(Navigator.class.getResource(Navigator.MEMBERSHIPPAYMENTFXML)));
						} catch (IOException e) {
							e.printStackTrace();
						}

					}
					else{
						message.setText(msg);
						message1.setTextFill(Color.GREEN);
					}
				}
				else{
					message.setText("login Id creation failed");
				}
			} catch (Exception e1) {
				e1.printStackTrace();
				message.setText("login Id creation failed");
			}
		}
	}

	@FXML
	public void backToLogin(ActionEvent event) throws IOException{
		Navigator.setPhoneNumber(null);
		FXMLLoader myLoader = new  FXMLLoader(getClass().getResource("/userManagementUI/LoginPage.fxml"));
		Stage MainStage = new Stage();
		Pane MainPagePane = (Pane)myLoader.load();
		LoginController controller = (LoginController) myLoader.getController();
		controller.SetStage(MainStage);
		Scene myScene = new Scene(MainPagePane);        
		MainStage.setScene(myScene);
		MainStage.setTitle("SUPERRENT");
		MainStage.setResizable(false);
		MainStage.setWidth(605);
		MainStage.setHeight(445);
		MainStage.show();
		createUserStage.close();
	}

	@FXML
	public void viewFaq(ActionEvent event){
		try {
			setCreateCustomerStackPane((Node) FXMLLoader.load(Navigator.class.getResource(Navigator.CREATELOGINFAQFXML)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	@FXML
	public void contactUs(ActionEvent event){
		try {
			setCreateCustomerStackPane((Node) FXMLLoader.load(Navigator.class.getResource(Navigator.CREATE_LOGIN_CONTACT_US_FXML)));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	/**
	 * This method is executed when system admin clicks submit button
	 * while creating an employee
	 * Precondition: system admin is creating an employee
	 * Postcondition: Employee is created
	 * @param event
	 * @throws IOException
	 */
	@FXML
	public void createEmploye(ActionEvent event) throws IOException
	{
		try
		{
		invalid=0;
		CreateUserLogic createLogic = new CreateUserLogic();
		
		// Validator.validateName
		if(name.getText().isEmpty())
		{
		    nameInvalid.setVisible(true);
		    invalid++;
		}
		else { nameInvalid.setVisible(false);
		if(!Validator.validateName(name.getText().trim())) {
			nameInvalid.setVisible(true);
			invalid++;
		}
		
		}
		
		// Validator.validatePhoneNumber
		if(phoneNumber.getText().isEmpty())
		{
		    phoneInvalid.setVisible(true);
		    invalid++;
		}
		else {
			phoneInvalid.setVisible(false);
			message2.setText("");
		if(Validator.validatePhoneNumber((phoneNumber.getText().trim()))){
		// checkphoneNumber
			
		if(!createLogic.checkPhoneNumber("+1".concat(phoneNumber.getText().trim()))) {
			phoneInvalid.setVisible(true);
			invalid++;
			message2.setText("Phone Number already exists");
		}}
		else
		{
			phoneInvalid.setVisible(true);
			invalid++;
		}}
		
		// Validator.validateEmailId
		if(emailAddress.getText().isEmpty()) {
			emailIdInvalid.setVisible(true);
			invalid++;
		}
		else {
			emailIdInvalid.setVisible(false);
			Emessage.setText("");
		if(!Validator.validateEmailID(emailAddress.getText().trim())) 
		{
			emailIdInvalid.setVisible(true);
			invalid++;
		}
		}
		
		// checkLoginId()
		if(loginId.getText().isEmpty()) {
			loginIdInvalid.setVisible(true);
			invalid++;
		}
		else {
			loginIdInvalid.setVisible(false);
			message4.setText("");
		if(!createLogic.checkLoginId(loginId.getText().trim()))
		{
			loginIdInvalid.setVisible(true);
			invalid++;
			message4.setText("Username not available");
		}}
	
		
		// Validator.verifypwd()
		if(pwd.getText().isEmpty() || confirmPwd.getText().isEmpty())
		{
			pwdInvalid.setVisible(true);
			confirmPwdInvalid.setVisible(true);
			invalid++;
		}
		else {
			pwdInvalid.setVisible(false);
			confirmPwdInvalid.setVisible(false);
			message.setText("");
		if(!Validator.verifyPwd(pwd.getText().trim(), confirmPwd.getText().trim()))
		{
			pwdInvalid.setVisible(true);
			confirmPwdInvalid.setVisible(true);
			invalid++;
			message.setText("Password and Confirm password does not match");
		}}
		
		if(address.getText().isEmpty())
		{
			addressInvalid.setVisible(true);
			invalid++;
		}
		else
			addressInvalid.setVisible(false);
		
		if(postalcode.getText().isEmpty())
		{
			postalInvalid.setVisible(true);
			invalid++;
		}
		else
			postalInvalid.setVisible(false);
		
		
		if(invalid>0)
		{
			message1.setText("Invalid entries");
		}
		else
		{
		//createEmployee()
	    EmployeeEntity empEntity = new EmployeeEntity();
	    empEntity.setName(name.getText());
	    String phNo = "+1";
	    phNo = phNo.concat(phoneNumber.getText().trim());
	    empEntity.setPhoneNumber(phNo);
	    empEntity.setEmailID(emailAddress.getText().trim());
	    empEntity.setAddress(address.getText().trim());
	    empEntity.setPincode(postalcode.getText().trim());
	    empEntity.setLoginId(loginId.getText().trim());
	    empEntity.setPwd(pwd.getText().trim());
	    if(designaton.getValue()==null)
	    {
	    	System.out.println("designation is null");
	    	designationInvalid.setVisible(true);
	    	invalid++;
	    	return;
	    }
	    else
	    {
	    if(designaton.getValue().equalsIgnoreCase("Manager"))
	    {
	    empEntity.setDesignation(Constants.MANAGER);
	    }
	    else
	    {
	    	empEntity.setDesignation(Constants.CLERK);
	    }}
	    boolean success = createLogic.createEmployee(empEntity);

		if(success){
			createEmployeSubmit.setDisable(true);
			if(empEntity.getEmailID() != null && !StringUtils.isEmpty(empEntity.getEmailID())){
					String text = "Dear Employee, Your login is successfully created by Admin. Your new login Id =" + empEntity.getLoginId() + " your password = " + Encrypt.decrypt(empEntity.getPwd());
					String subject = "Your Login Id for SuperRent";
					MailSender.send(text, subject, empEntity.getEmailID());
			}
	 
	    message1.setText("Employee Created");
	    message1.setTextFill(Color.GREEN);
	    emailIdInvalid.setVisible(false);
	    phoneInvalid.setVisible(false);
	    addressInvalid.setVisible(false);
	    loginIdInvalid.setVisible(false);
	    designationInvalid.setVisible(false);
	    nameInvalid.setVisible(false);
	    pwdInvalid.setVisible(false);
	    confirmPwdInvalid.setVisible(false);
	    postalInvalid.setVisible(false);
	    System.out.println("Employee created");
	    
	    // send email
		}}
		}
		catch (SQLException e) {
			e.printStackTrace();
			message1.setText("Connection failed..Try Again!");
		} catch (Exception e) {
			e.printStackTrace();
			message1.setText("Connection failed..Try Again!");
		}

	}

	
	@Override
	public void initialize(URL location, ResourceBundle resources) {
		// TODO Auto-generated method stub
		Validator.addTextLimiter(name, 30);
		Validator.addTextLimiter(phoneNumber, 10);
		Validator.addTextLimiter(emailAddress, 40);
		Validator.addTextLimiter(address, 30);
		Validator.addTextLimiter(postalcode, 6);
		Validator.addTextLimiter(loginId, 10);
		Validator.addTextLimiter(pwd, 15);
		Validator.addTextLimiter(confirmPwd, 15);
	}

}

